use crate::components::{clear::Clear, copy::Copy};
use dioxus::prelude::*;

#[component]
pub fn TextDiff() -> Element {
    let mut text_a = use_signal(|| String::new());
    let mut text_b = use_signal(|| String::new());
    let mut diff_result = use_signal(|| Vec::<(usize, String, String)>::new());

    let mut compare = move || {
        let binding_a = text_a.read();
        let a_lines: Vec<_> = binding_a.lines().collect();
        let binding_b = text_b.read();
        let b_lines: Vec<_> = binding_b.lines().collect();
        let max_len = a_lines.len().max(b_lines.len());

        let mut diffs = vec![];

        for i in 0..max_len {
            let a_line = a_lines.get(i).unwrap_or(&"");
            let b_line = b_lines.get(i).unwrap_or(&"");

            let a_chars: Vec<char> = a_line.chars().collect();
            let b_chars: Vec<char> = b_line.chars().collect();
            let max_char_len = a_chars.len().max(b_chars.len());

            let mut styled_a = String::new();
            let mut styled_b = String::new();

            for j in 0..max_char_len {
                let a_char = a_chars.get(j).copied().unwrap_or(' ');
                let b_char = b_chars.get(j).copied().unwrap_or(' ');

                if a_char == b_char {
                    styled_a.push(a_char);
                    styled_b.push(b_char);
                } else {
                    styled_a.push_str(&format!(
                        "<mark style=\"background-color: #ffe4e6\">{}</mark>",
                        a_char
                    ));
                    styled_b.push_str(&format!(
                        "<mark style=\"background-color: #dbeafe\">{}</mark>",
                        b_char
                    ));
                }
            }

            if styled_a != styled_b {
                diffs.push((i + 1, styled_a, styled_b));
            }
        }

        diff_result.set(diffs);
    };

    rsx! {
        div { class: "flex-1 flex flex-col",
            div { class: "flex-1 p-8 overflow-auto",
                div { class: "max-w-4xl mx-auto space-y-6",
                    div { class: "space-y-2",
                        h1 { class: "text-2xl font-bold text-gray-900", "文本对比" }
                        p { class: "text-gray-600", "对比两个文本内容差异" }
                    }
                    div { class: "flex flex-col gap-y-6 w-full",

                        textarea {
                            oninput:move |e| text_a.set(e.value()),
                            value:text_a,
                            width:"100%",
                            spellcheck: "false",              // 关闭拼写检查
                               autocapitalize: "off",            // 关闭首字母自动大写
                               autocomplete: "off",              // 关闭自动补全
                                   box_sizing: "border-box",  // 添加这行
                                            // 确保宽度匹配
                                   class: "flex w-full border bg-background px-3 py-2 ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 min-h-[120px] rounded-xl border-gray-200 resize-none font-mono text-sm",
                                   placeholder: "魔法师",
                        }

                        textarea {
                            oninput:move |e| text_b.set(e.value()),
                            value:text_b,
                            spellcheck: "false",              // 关闭拼写检查
                               autocapitalize: "off",            // 关闭首字母自动大写
                               autocomplete: "off",              // 关闭自动补全
                               box_sizing: "border-box",  // 添加这行
                               width: "100%",
                            class: "flex w-full border bg-background px-3 py-2 ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 min-h-[120px] rounded-xl border-gray-200 resize-none font-mono text-sm",
                             placeholder: "魔法师",
                        }

                    }
                    div { class: "flex items-center space-x-3",
                        button {
                            onclick: move |_| compare(),
                            class: "bg-blue-600 text-white px-6 py-2 rounded-xl hover:bg-blue-700 transition-all text-sm",
                            "对比"
                        }
                        Clear { targets: vec![text_a.clone(), text_b.clone()] }
                    }

                    if !diff_result.read().is_empty() {
                        div {
                            class: "border border-gray-200 rounded-2xl shadow-sm overflow-auto",
                            div { class: "p-4 flex justify-between items-center",
                                h2 { class: "text-lg font-semibold text-gray-900", "不同项总数: {diff_result.read().len()}" }
                            }


                            table {
                                class: "min-w-full text-sm table-fixed border rounded-md overflow-hidden",
                                thead {
                                    tr { class: "bg-gray-100 border-b w-full",
                                        th { class: "text-left font-semibold text-gray-800 px-4 py-2", style: "width: 10%;" , "行号" }
                                        th { class: "text-left font-semibold text-gray-800 px-4 py-2", style: "width: 45%;" , "文本A" }
                                        th { class: "text-left font-semibold text-gray-800 px-4 py-2", style: "width: 45%;" , "文本B" }
                                    }
                                }
                                tbody {
                                    for (i, a, b) in diff_result.read().iter() {
                                        tr {
                                            class: if i % 2 == 0 {
                                                "bg-white hover:bg-gray-50"
                                            } else {
                                                "bg-gray-50 hover:bg-gray-100"
                                            },
                                            td { class: "px-4 py-2 text-gray-700 truncate", "{i}" }
                                            td { class: "text-gray-900 pr-4 py-2 break-words", dangerous_inner_html:a.as_str() }
                                            td { class: "text-gray-700 py-2 break-words", dangerous_inner_html:b.as_str() }
                                        }
                                    }
                                }
                            }




                        }
                    } else if *text_a.read().to_string() == *text_b.read().to_string() && (!text_a.read().is_empty() && !text_b.read().is_empty()) {
                        div { class: "text-green-600 font-medium", "两个文本完全一致 ✅" }
                    }
                }
            }
        }
    }
}
